<template>
  <div class="report">
    <tableTool>
      <div slot="export">
        <el-button type="primary" @click="excelExport">导出</el-button>
      </div>

      <div class="tool-form" slot="form">
        <div class="input-group">
          <span class="lable">设备名称：</span>
          <el-input placeholder="请输入" v-model="search.equipmentName" />
        </div>
        <div class="input-group">
          <span class="lable">设备类别：</span>
          <el-input
            placeholder="请输入"
            v-model="search.equipmentCategoryName"
          />
        </div>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button type="success" @click="onReset">重置</el-button>
      </div>
    </tableTool>
    <customTable :list="list" :combined="combined">
      <template v-slot:title>
        <tr>
          <th colspan="12">{{ equipmentCategoryName }}</th>
        </tr>
        <tr>
          <th colspan="12" style="text-align: right">
            机构、设备类别、设备编号、设备名称、设备状态、月份
          </th>
        </tr>
        <tr>
          <th>设备编号</th>
          <th>设备名称</th>
          <th>规格型号</th>
          <th>设备状态</th>
          <th>生产厂商</th>
          <th>生产日期</th>
          <th>累计使用数</th>
          <th>计数单位</th>
          <th>维修保养费</th>
          <th>油耗量（L）</th>
          <th>利用率（%）</th>
          <th>故障率（%）</th>
        </tr>
      </template>
      <template #body="{ list }">
        <tr v-for="item in list" :key="item.equipmentSerialNumber">
          <td>{{ item.equipmentSerialNumber }}</td>
          <td>{{ item.equipmentName }}</td>
          <td>{{ item.equipmentModel }}</td>
          <td>{{ item.equipmentState }}</td>
          <td>{{ item.manufacturer }}</td>
          <td>{{ item.productionDate }}</td>
          <td>{{ item.cumulativeUse }}</td>
          <td>{{ item.countUnit }}</td>
          <td>{{ item.maintenanceCost }}</td>
          <td>{{ item.fuelConsumption }}</td>
          <td>{{ item.utilization }}</td>
          <td>{{ item.failureRate }}</td>
        </tr>
      </template>
      <template #empty>
        <tr>
          <td colspan="12" class="empty">暂无数据</td>
        </tr>
      </template>
      <template #footer="{ combined }">
        <tr>
          <td>合计</td>
          <td>{{ combined.equipmentName }}</td>
          <td>{{ combined.equipmentModel }}</td>
          <td>{{ combined.equipmentState }}</td>
          <td>{{ combined.manufacturer }}</td>
          <td>{{ combined.productionDate }}</td>
          <td>{{ combined.cumulativeUse }}</td>
          <td>{{ combined.countUnit }}</td>
          <td>{{ combined.maintenanceCost }}</td>
          <td>{{ combined.fuelConsumption }}</td>
          <td>{{ combined.utilization }}</td>
          <td>{{ combined.failureRate }}</td>
        </tr>
      </template>
    </customTable>
    <pagination
      @onCurrentChange="handleCurrentChange"
      :total="page.total"
      :limit="page.limit"
    ></pagination>
  </div>
</template>
<script>
import tableTool from "../components/tableTool.vue";
import customTable from "../components/customTable.vue";
import pagination from "../components/pagination.vue";
import request from "@/api/comprehensiveReport/equipmentManagement.js";
import {
  combinedFn,
  formatTime,
} from "@/pages/comprehensiveReport/equipmentManagement/mixin";
export default {
  name: "generalLedgerProject",
  components: { tableTool, customTable, pagination },
  data() {
    return {
      list: [],
      page: {
        total: 0,
        currentPage: 1,
        limit: 10,
      },
      search: {
        equipmentCategoryName: "",
        equipmentName: "",
      },
      equipmentCategoryName:
        this.$route.query.equipmentCategoryName ||
        this.$store.state.userInfo.orgInfo.orgName,
      orgId:
        this.$route.query.orgId || this.$store.state.userInfo.orgInfo.orgId,
      equipmentCategoryId: this.$route.query.equipmentCategoryId || "",
      combined: {},
      headers: {
        设备编号: "equipmentSerialNumber",
        设备名称: "equipmentName",
        规格型号: "equipmentModel",
        设备状态: "equipmentState",
        生产厂商: "manufacturer",
        生产日期: "productionDate",
        累计使用数: "cumulativeUse",
        计数单位: "countUnit",
        维修保养费: "maintenanceCost",
        油耗量: "fuelConsumption",
        利用率: "utilization",
        故障率: "failureRate",
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    onSearch() {
      this.getList();
      this.onReset();
    },
    onReset() {
      this.search = {
        equipmentCategoryName: "",
        equipmentName: "",
      };
    },
    async getList() {
      // 如果是分子公司点进来的，就获取路由中的orgId、equipmentCategoryId
      // 如果是项目层登录的，就去Vuex中去取公司/机构ID、不传设备类别ID
      const res = await request.getProjectCompany({
        orgId: this.orgId,
        pageSize: this.page.limit,
        pageNo: this.page.currentPage,
        equipmentCategoryId: this.equipmentCategoryId,
        orgType: this.$store.state.userInfo.orgInfo.orgType,
        equipmentCategoryName: this.search.equipmentCategoryName, // 查询设备类别
        equipmentName: this.search.equipmentName, // 查询设备名称
      });

      console.log("发送请求，获取数据", res);
      if (res.data == null) {
        this.list = []
        this.combined = {}
        this.page.total = 0
        return;
      }
      this.page.total = res.totalCount;
      const { list, combined } = combinedFn(
        Object.values(this.headers).slice(1),
        res.data,
        ["maintenanceCost", "utilization", "failureRate", "fuelConsumption"]
      );
      this.list = this.stateConvert(formatTime(["productionDate"], list));
      this.combined = combined;
    },
    handleCurrentChange(currentPage) {
      console.log(`当前页: 第${currentPage}页`);
      this.page.currentPage = currentPage;
      this.getList();
    },
    excelExport() {
      const multiHeader = [
        [
          this.equipmentCategoryName,
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
        ],
        [
          "机构、设备类别、设备编号、设备名称、设备状态、月份",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
        ],
      ];
      const merges = ["A1:L1", "A2:L2"];
      import("@/utils/Export2Excel.js").then(async (excel) => {
        const { data: res } = await request.getProjectCompany({
          orgId: this.orgId,
          pageSize: this.page.total,
          pageNo: 1,
          equipmentCategoryId: this.equipmentCategoryId,
          orgType: this.$store.state.userInfo.orgInfo.orgType,
        });

        const { list, combined } = combinedFn(
          Object.values(this.headers).slice(1),
          res,
          ["maintenanceCost", "utilization", "failureRate", "fuelConsumption"]
        );
        const data = this.formatJson(
          this.headers,
          this.stateConvert(formatTime(["productionDate"], list))
        );
        data.push(["合计", ...Object.values(combined)]);
        excel.export_json_to_excel({
          header: Object.keys(this.headers),
          data,
          filename: `设备管理-设备总账-${this.equipmentCategoryName}`,
          autoWidth: true,
          bookType: "xlsx",
          multiHeader,
          merges,
        });
      });
    },
    formatJson(headers, list) {
      return list.map((item) => {
        return Object.values(headers).map((value) => {
          return item[value];
        });
      });
    },
    stateConvert(list) {
      const state = {
        0: "闲置",
        1: "待班",
        2: "运转",
        3: "已外租",
        4: "维修保养中",
        5: "事故中",
        6: "报废中",
        7: "已报废",
        8: "处置中",
        9: "已处置",
        10: "技改中",
        11: "已退场",
        12: "丢失",
      };
      return list.map((item) => {
        item["equipmentState"] = state[item["equipmentState"]];
        return item;
      });
    },
  },
};
</script>
<style lang="scss"></style>
